package com.absir.uniplugin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AbCenter {

    static AbCenter me;

    public static AbCenter ME() {
        if (me == null) {
            me = new AbCenter();
        }

        return me;
    }

    Map<String, IListener> listenerMap;

    List<IListener> listenerList;

    public IListener reg(String event, IListener listener) {
        if (listenerMap == null) {
            listenerMap = new HashMap<>();
        }

        return listenerMap.put(event, listener);
    }

    public IListener unReg(String event) {
        return listenerMap == null ? null : listenerMap.remove(event);
    }

    public boolean addListener(IListener listener) {
        if (listenerList == null) {
            listenerList = new ArrayList<>();
        }

        return listenerList.add(listener);
    }

    public boolean removeListener(IListener listener) {
        return listenerList == null ? false : listenerList.remove(listener);
    }

    public void postEvent(String event, String paras) {
        try {
            if (listenerMap != null) {
                IListener listener = listenerMap.get(event);
                if (listener != null) {
                    listener.onEvent(event, paras);
                }
            }

        } finally {
            if (listenerList != null) {
                postEventNext(event, paras, 0);
            }
        }
    }

    protected void postEventNext(String event, String paras, int i) {
        if (i < listenerList.size()) {
            try {
                listenerList.get(i).onEvent(event, paras);

            } finally {
                postEventNext(event, paras, ++i);
            }
        }
    }
}
